package com.zhang.authoritycenter.common.util;


import com.zhang.infrastructure.model.KingHoodExceptionUtil;
import com.zhang.authoritycenter.common.model.dto.auth.KingHoodPrincipal;
import com.zhang.authoritycenter.common.model.dto.auth.UserDTO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2023-12-07 23:54
 **/
public class UserUtil {

    public static KingHoodPrincipal get() {

        Authentication authentication0 = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken authentication = null;
        if (authentication0 instanceof UsernamePasswordAuthenticationToken) {
            authentication = (UsernamePasswordAuthenticationToken) authentication0;
        } else {
            return null;
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof KingHoodPrincipal) {
            KingHoodPrincipal kingHoodPrincipal = (KingHoodPrincipal) principal;
            return kingHoodPrincipal;
        }
        return null;
    }

    public static UserDTO getUser() {
        KingHoodPrincipal kingHoodPrincipal = get();
        if (Objects.isNull(kingHoodPrincipal)) {
            return null;
        }
        KingHoodExceptionUtil.isNull(kingHoodPrincipal.getAudience(), "token信息异常");
        UserDTO user = new UserDTO();
        user.setIssuer(kingHoodPrincipal.getIssuer());
        user.setId(new Long(kingHoodPrincipal.getAudience()));
        user.setUsername(kingHoodPrincipal.getSubject());

        return user;
    }

    public static Long getUserId() {
        UserDTO user = getUser();
        if (Objects.isNull(user)) {
            return null;
        }
        return user.getId();
    }
}
